#include <QCoreApplication>

#include <QDebug>
#include <QHostAddress>
#include <QTcpServer>

#include "manager.h"

int main(int argc, char *argv[]) {
  QCoreApplication a(argc, argv);
  quint16 port = 7777;
  if (argc >= 2)
    port = QString::fromLocal8Bit(argv[1]).toUShort();

  QTcpServer tcpServer;
  if (!tcpServer.listen(QHostAddress("0.0.0.0"), port)) {
    qCritical() << __FUNCTION__ << __func__ << "Listen error" << port;
    return 0;
  }

  QObject::connect(&tcpServer, &QTcpServer::newConnection, [&tcpServer]() {
    while (tcpServer.hasPendingConnections()) {
      QTcpSocket *client = tcpServer.nextPendingConnection();
      Manager::instance()->addClient(client);
    }
  });

  qDebug() << "Start app listening on port" << tcpServer.serverPort();
  return a.exec();
}
